﻿using FRMS.BUS;
using FRMS.DAL;
using FRMS.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FRMS.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class UploadController : ControllerBase
    {
        [Obsolete]
        private readonly IHostingEnvironment _hostingEnvironment;
        private JwtSettings _jwtSettings;
        IHttpContextAccessor _access;

        [Obsolete]
        public UploadController(IHostingEnvironment hostingEnvironment, IOptions<JwtSettings> jwtSettingsAccesser, IHttpContextAccessor access)
        {
            _hostingEnvironment = hostingEnvironment;
            JwtSettings jwt = new JwtSettings();
            jwt.Audience = AppSettingsHelper.Configuration["JwtSettings:Audience"];
            jwt.Issuer = AppSettingsHelper.Configuration["JwtSettings:Issuer"];
            jwt.SecretKey = AppSettingsHelper.Configuration["JwtSettings:SecretKey"];
            _jwtSettings = jwt;
            _access = access;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("UpLoadPic")]
        [Obsolete]
        public ResponseMessage UpLoadPic([FromForm] IFormCollection formCollection)
        {
            ResponseMessage message = new ResponseMessage();
            string webRootPath = _hostingEnvironment.ContentRootPath;
            List<UploadFileEntity> uploadFileList = new List<UploadFileEntity>();
            FormFileCollection filelist = (FormFileCollection)formCollection.Files;
            try
            {
                foreach (IFormFile file in filelist)
                {
                    UploadFileEntity content = new UploadFileEntity();

                    String Tpath = "/img/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
                    string name = file.FileName;
                    string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string FilePath = webRootPath + "/wwwroot" + Tpath;

                    string type = System.IO.Path.GetExtension(name);
                    DirectoryInfo di = new DirectoryInfo(FilePath);


                    if (!di.Exists) { di.Create(); }

                    using (FileStream fs = System.IO.File.Create(FilePath + FileName + type))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                        fs.Close();
                        content.FileName = FileName + type;
                        content.FilePath = Tpath;
                    }

                    uploadFileList.Add(content);
                }
                message.errcode = 0;
                message.errmsg = "";
                message.data = uploadFileList;
                message.total = 1;
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString());
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "上传图片";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "上传图片失败";
                message.data = null;
                message.total = 0;
            }

            return message;
        }

        /*        /// <summary>
                /// 导入楼栋信息
                /// </summary>
                /// <returns></returns>
                [HttpPost]
                [Route("ImportBuild")]
                //[Obsolete]
                public ResponseMessage ImportBuild([FromForm] IFormCollection formCollection)
                {
                    ResponseMessage message = new ResponseMessage();
                    try
                    {
                        int projectid = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                        string webRootPath = _hostingEnvironment.ContentRootPath;

                        FormFileCollection filelist = (FormFileCollection)formCollection.Files;
                        foreach (IFormFile file in filelist)
                        {
                            DataTable data = new DataTable();
                            string filepath = ExcelTools.UploadFileToServer(file, webRootPath);
                            string name;
                            string code;
                            data = ExcelTools.ImportCompareMeanExcel(filepath, out name, out code);
                            if (name.Replace(" ", "") != "单元楼栋管理")
                            {
                                message.errcode = 1;
                                message.errmsg = "工作表名校验失败";
                            }
                            else if (code.Replace(" ", "") != "funstar")
                            {
                                message.errcode = 1;
                                message.errmsg = "验证码错误";
                            }
                            else
                            {
                                message = ExcelTools.ImportBuildToData(data, projectid);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        message.errcode = 1;
                        message.errmsg = "导入楼栋信息失败";
                        message.data = "";
                        message.total = 0;
                    }
                    return message;
                }*/

        /* /// <summary>
         /// 导入房间信息
         /// </summary>
         /// <returns></returns>
         [HttpPost]
         [Route("ImportRoom")]
         [Obsolete]
         public ResponseMessage ImportRoom([FromForm] IFormCollection formCollection, int projectid)
         {
             ResponseMessage message = new ResponseMessage();
             try
             {
                 string webRootPath = _hostingEnvironment.ContentRootPath;

                 FormFileCollection filelist = (FormFileCollection)formCollection.Files;
                 foreach (IFormFile file in filelist)
                 {
                     DataTable data = new DataTable();
                     string filepath = ExcelTools.UploadFileToServer(file, webRootPath);
                     string name;
                     string code;
                     data = ExcelTools.ImportCompareMeanExcel(filepath, out name, out code);
                     if (name.Replace(" ", "") != "房间管理")
                     {
                         message.errcode = 1;
                         message.errmsg = "工作表名校验失败";
                     }
                     else if (code.Replace(" ", "") != "funstar")
                     {
                         message.errcode = 1;
                         message.errmsg = "验证码错误";
                     }
                     else
                     {
                         message = ExcelTools.ImportBuildToData(data, projectid);
                     }
                 }
             }
             catch (Exception e)
             {
                 message.errcode = 1;
                 message.errmsg = "导入楼栋信息失败";
                 message.data = "";
                 message.total = 0;
             }
             return message;
         }*/

        /// <summary>
        /// 一键导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("OneClickImport")]
        [Obsolete]
        public ResponseMessage OneClickImport([FromForm] IFormCollection formCollection, string type, int deviceId)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                string webRootPath = _hostingEnvironment.ContentRootPath;
                int projectid = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                bool flag = false;
                DataDAL da = new DataDAL();
                FormFileCollection filelist = (FormFileCollection)formCollection.Files;
                foreach (IFormFile file in filelist)
                {
                    if (type == "all")
                    {
                        /*bool result = da.ClearAll(projectid);
                        if (result)
                        {*/
                        message = ImportAll(webRootPath, file, projectid);
                        flag = true;
                        /*}
                        else
                        {
                            message.errcode = 1;
                            message.errmsg = "数据清空异常，一键导入失败";
                        }*/
                    }
                    else if (type == "build")
                    {
                        /*bool result = da.ClearAll(projectid);
                        if (result)
                        {*/
                        string filepath = ExcelTools.UploadFileToServer(file, webRootPath);
                        DataTable data = ExcelTools.ImportCompareMeanExcel(filepath, 0);
                        message = ExcelTools.ImportBuild(data, projectid);
                        flag = true;
                        /*}
                        else
                        {
                            message.errcode = 1;
                            message.errmsg = "数据清空异常，导入楼栋单元失败";
                        }*/
                    }
                    else if (type == "elevator")
                    {
                        /*bool result = da.ClearElevator(projectid);
                        if (result)
                        {*/
                        string filepath = ExcelTools.UploadFileToServer(file, webRootPath);
                        DataTable data = ExcelTools.ImportCompareMeanExcel(filepath, 1);
                        message = ExcelTools.ImportElevator(data, projectid);
                        flag = true;
                        /*}
                        else
                        {
                            message.errcode = 1;
                            message.errmsg = "数据清空异常，导入电梯失败";
                        }*/
                    }
                    else if (type == "room")
                    {
                        /* bool result = da.ClearRoom(projectid);
                         if (result)
                         {*/
                        string filepath = ExcelTools.UploadFileToServer(file, webRootPath);
                        DataTable data = ExcelTools.ImportCompareMeanExcel(filepath, 2);
                        message = ExcelTools.ImportRoom(data, projectid);
                        /*}
                        else
                        {
                            message.errcode = 1;
                            message.errmsg = "数据清空异常，导入房间失败";
                        }*/
                    }
                    else if (type == "device")
                    {
                        string filepath = ExcelTools.UploadFileToServer(file, webRootPath);
                        DataTable data = ExcelTools.ImportCompareMeanExcel(filepath, 3);
                        message = ExcelTools.ImportDevice(data, projectid);
                        flag = true;
                    }
                    else if (type == "owner")
                    {
                        VoucherBUS BUS = new VoucherBUS();
                        //message = BUS.JLVoucherClearAll(deviceId, 0);
                        if (message.errcode == 0)
                        {
                            /* bool result = da.ClearOwner(projectid);
                             if (result)
                             {*/
                            string filepath = ExcelTools.UploadFileToServer(file, webRootPath);
                            DataTable data = ExcelTools.ImportCompareMeanExcel(filepath, 4);
                            message = ExcelTools.ImportOwner(data, projectid, webRootPath);
                            flag = true;
                            /*}
                            else
                            {
                                message.errcode = 1;
                                message.errmsg = "数据清空异常，导入业主失败";
                            }*/
                        }
                    }
                }
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "一键导入";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "一键导入异常";
                message.data = "";
                message.total = 0;
            }
            return message;
        }

        public ResponseMessage ImportAll(string webRootPath, IFormFile file, int projectid)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DataTable data = new DataTable();
                string filepath = ExcelTools.UploadFileToServer(file, webRootPath);
                for (int i = 0; i < 4; i++)
                {
                    data = ExcelTools.ImportCompareMeanExcel(filepath, i);
                    if (i == 0)
                    {
                        message = ExcelTools.ImportBuild(data, projectid);
                        if (message.errcode == 1)
                        {
                            return message;
                        }
                    }
                    else if (i == 1)
                    {
                        message = ExcelTools.ImportElevator(data, projectid);
                        if (message.errcode == 1)
                        {
                            return message;
                        }

                    }
                    else if (i == 2)
                    {
                        message = ExcelTools.ImportRoom(data, projectid);
                        if (message.errcode == 1)
                        {
                            return message;
                        }
                    }
                    else if (i == 3)
                    {
                        message = ExcelTools.ImportDevice(data, projectid);
                        if (message.errcode == 1)
                        {
                            return message;
                        }
                    }
                    else if (i == 3)
                    {
                        message = ExcelTools.ImportOwner(data, projectid, webRootPath);
                        if (message.errcode == 1)
                        {
                            return message;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "一键导入";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "一键导入异常";
            }
            return message;
        }

        /// <summary>
        /// 清除数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ClearData")]
        public ResponseMessage ClearData(string type)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DataClearBUS bUS = new DataClearBUS();
                int projectid = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                if (type == "build")
                {
                    message = bUS.ClearBuild(projectid);
                }
                else if (type == "room")
                {
                    message = bUS.ClearRoom(projectid);
                }
                else if (type == "elevator")
                {
                    message = bUS.ClearElevator(projectid);
                }
                else if (type == "device")
                {
                    message = bUS.ClearDevice(projectid);
                }
                else if (type == "owner")
                {
                    message = bUS.ClearOwner(projectid);
                }
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "清除数据";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "清除失败";
                message.data = null;
                message.total = 0;
            }

            return message;
        }

        /// <summary>
        /// 清除业主
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ClearOwner")]
        public ResponseMessage ClearOwner()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DataClearBUS bUS = new DataClearBUS();
                int projectid = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                message = bUS.ClearOwner(projectid);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "清除业主";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "清除业主失败";
                message.data = null;
                message.total = 0;
            }

            return message;
        }

        /// <summary>
        /// 清除设备
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ClearDevice")]
        public ResponseMessage ClearDevice()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DataClearBUS bUS = new DataClearBUS();
                int projectid = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                message = bUS.ClearDevice(projectid);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "清除设备";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "清除设备失败";
                message.data = null;
                message.total = 0;
            }

            return message;
        }

        /// <summary>
        /// 清除电梯
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ClearElevator")]
        public ResponseMessage ClearElevator()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DataClearBUS bUS = new DataClearBUS();
                int projectid = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                message = bUS.ClearElevator(projectid);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "清除电梯";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "清除电梯失败";
                message.data = null;
                message.total = 0;
            }

            return message;
        }

        /// <summary>
        /// 清除房间
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ClearRoom")]
        public ResponseMessage ClearRoom()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DataClearBUS bUS = new DataClearBUS();
                int projectid = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                message = bUS.ClearRoom(projectid);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "清除房间";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "清除房间失败";
                message.data = null;
                message.total = 0;
            }

            return message;
        }

        /// <summary>
        /// 清除楼栋
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ClearBuild")]
        public ResponseMessage ClearBuild()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DataClearBUS bUS = new DataClearBUS();
                int projectid = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                message = bUS.ClearBuild(projectid);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "清除楼栋";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "清除楼栋失败";
                message.data = null;
                message.total = 0;
            }

            return message;
        }
    }
}
